import { getToken, setToken } from '../utils/auth'
import NProgress from 'nprogress'
import { Notification } from 'element-ui'
import store from '../store'
import router from './index'
import { fetchRoutesFromMenu } from '../utils/router'

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 白名单
  if (to.matched.some(r => r.meta.isAnonymous)) {
    next()
  } else {
    const _token = to.query.token
    if (_token) {
      setToken(_token)
    }
    const token = getToken()
    if (token) {
      if (!store.state.auth.user || !Object.keys(store.state.auth.user).length) {
        store.dispatch('getUserProfile').then(() => {
          const appId = store.state.base.app.id
          if (!appId) {
            Notification.error({
              title: '错误',
              message: '请先添加应用配置'
            })
            return
          }
          store.dispatch('getMenu', {
            appIds: [appId]
          }).then((res) => {
            fetchRoutesFromMenu(store.state.auth.menu, router)
            next({
              ...to,
              replace: true
            })
          })
        })
      } else {
        next()
      }
    } else {
      // 未登录
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  }
})

router.afterEach((to) => {
  NProgress.done()
  document.title = (to.meta.title ? to.meta.title + ' - ' : '') + store.state.base.app.appName || ''
  window.scrollTo(0, 0)
})
